#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct pessoa
{
	char nome[30];
	int idade;
	float renda;
} pessoa;

main(int argc, char *argv[])
{
	int mpierr, rank, size, position, tambuf, tambuftmp, i, tag;
	MPI_Status status;
	char *message;
	pessoa p1;
	
	mpierr = MPI_Init(&argc, &argv);
	tag = 111;
	
	if (mpierr >= 0)
	{
		MPI_Comm_rank(MPI_COMM_WORLD, &rank);
		MPI_Comm_size(MPI_COMM_WORLD, &size);
		
		tambuf=0;
		MPI_Pack_size(30, MPI_CHAR, MPI_COMM_WORLD, &tambuftmp);
		tambuf=tambuf+tambuftmp;
		MPI_Pack_size(1, MPI_INT, MPI_COMM_WORLD, &tambuftmp);
		tambuf=tambuf+tambuftmp;
		MPI_Pack_size(1, MPI_FLOAT, MPI_COMM_WORLD, &tambuftmp);
		tambuf=tambuf+tambuftmp;
		//message = (char*) malloc(tambuf*sizeof(char));
		message = (char*) malloc(500);
		message[0] = '\0';

		
		if (rank == 0)
		{
			strcpy(p1.nome,"Joao da Silva");
			p1.idade=35;
			p1.renda=1235.50;
			MPI_Pack(p1.nome, 30, MPI_CHAR, message, 100, &position, MPI_COMM_WORLD);
			MPI_Pack(&p1.idade, 1, MPI_INT, message, 100, &position, MPI_COMM_WORLD);
			MPI_Pack(&p1.renda, 1, MPI_FLOAT, message, 100, &position, MPI_COMM_WORLD);
			
			for (i=1; i<size; i++)
				MPI_Send(message, tambuf, MPI_PACKED, i, tag, MPI_COMM_WORLD);
		}
		else
		{
			MPI_Recv(message, tambuf, MPI_PACKED, 0, tag, MPI_COMM_WORLD, &status);
		}
		
		printf("Mensagem do processo' %d : %s\n", rank, message);
		MPI_Finalize();
	}
}
